package jpb.module.service.load;

import jpb.constant.UpState;
import jpb.module.dao.department.DepartmentDao;
import jpb.module.dao.member.MemberDao;
import jpb.module.dao.member.MemberLogDao;
import jpb.module.dao.organize.OrganizeDao;
import jpb.module.dao.profession.ProfessionDao;
import jpb.module.daomain.department.Department;
import jpb.module.daomain.department.LoadDep;
import jpb.module.daomain.member.LoadMem;
import jpb.module.daomain.member.Member;
import jpb.module.daomain.organize.Organize;
import jpb.module.daomain.profession.Profession;
import jpb.module.service.manager.ManagerService;
import jpb.util.DateFormatUtil;
import jpb.util.IndexUtil;
import jpb.util.load.LoadExcelUtil;
import jpb.util.load.FileUpLoadUtil;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by haol on 2017/4/13.
 */
@Service
public class LoadService {
        @Autowired
        private DepartmentDao departmentDao;
        @Autowired
        private OrganizeDao organizeDao;
        @Autowired
        private ProfessionDao professionDao;
        @Autowired
        private ProofMessageService proofMessageService;
        @Autowired
        private ManagerService managerService;
        @Autowired
        private MemberDao memberDao;
        @Autowired
        private MemberLogDao memberLogDao;


        LoadExcelUtil loadExcelUtil = new LoadExcelUtil();

        private Logger logger = LoggerFactory.getLogger(LoadService.class);

        public void buildExcel(String oid, String path, String fileName, String[] head) {
                long startTime = System.currentTimeMillis();
                String[] pros =new String[]{};
                Organize organize = organizeDao.get(oid);
                List<Department> departments = departmentDao.getLeaf(oid);
                String name = organize.getName() + "(" + organize.getMark() + ")";
                if (organize.getType() != 2) {
                        List<Profession> professions = professionDao.getByOid(oid);
                        pros = new String[professions.size()];
                        for (int i = 0; i < professions.size(); i++) {
                                pros[i] = professions.get(i).getName();
                        }
                }
                HSSFWorkbook   workbook = loadExcelUtil.create(
                        departments, name, organize.getId(), head, pros);

                this.download(workbook, path, fileName);

                long endTime = System.currentTimeMillis();
                logger.info("构建Excel表格共花费{}毫秒", endTime - startTime);
        }


        public void buildExcelConMem(String oid, String path, String fileName, String[] head) {
                long startTime = System.currentTimeMillis();

                Organize organize = organizeDao.get(oid);
                List<Department> departments = departmentDao.getLeaf(oid);
                String name = organize.getName() + "(" + organize.getMark() + ")";
                List<LoadDep> loadDeps = new ArrayList<LoadDep>();


                for (Department department:departments){
                        LoadDep loadDep = new LoadDep();
                        List<LoadMem> members = memberDao.getDetailByDid(department.getId());
                        loadDep.setMembers(members);
                        loadDeps.add(loadDep);
                }

                this.addOtherMsg(loadDeps);
                HSSFWorkbook   workbook = loadExcelUtil.create(
                        loadDeps, name, organize.getId(), head);

                this.download(workbook, path, fileName);

                long endTime = System.currentTimeMillis();
                logger.info("构建Excel表格共花费{}毫秒", endTime - startTime);
        }

        public List<LoadDep> addOtherMsg(List<LoadDep> loadDeps){

                for (LoadDep loadDep:loadDeps){
                        for (LoadMem loadMem:loadDep.getMembers()){
                                Member mem = memberDao.get(loadMem.getMemberNum());
//                                if (mem.getMemberNum().equals("201430098009")){
//                                        System.out.println();
//                                }
                                if (mem.getLoginTime() != null){
                                        loadMem.setLoginTime(mem.getLoginTime());
                                }
                                String mobiles = "";
                                if (mem.getMobiles().size() != 0){
                                        for (String mobile:mem.getMobiles()){
                                                mobiles = mobiles+mobile+"/";
                                        }
                                        mobiles = mobiles.substring(0,mobiles.length()-1);
                                }
                                loadMem.setMobile(mobiles);

                        }
                }
                return loadDeps;
        }

        public void buildExcel(String path, String fileName, String[] head) {

                long startTime = System.currentTimeMillis();

                HSSFWorkbook workbook = loadExcelUtil.create(head);

                this.download(workbook, path, fileName);

                long endTime = System.currentTimeMillis();
                logger.info("构建Excel表格共花费{}毫秒", endTime - startTime);
        }


        public void download(HSSFWorkbook workbook, String path, String fileName) {
                try {
                        FileOutputStream outputStream = new FileOutputStream(path + fileName);
                        workbook.write(outputStream);
                        outputStream.close();
                        logger.info("文件[{}]生成到本地[{}]", fileName, path);
                } catch (Exception e) {
                        e.printStackTrace();
                }

        }

//        public List<Leaguer> handleExcelCom(HSSFWorkbook workbook, String[] head) {
//                long startTime = System.currentTimeMillis();
//
//                HashMap<String, Object> titleMap = loadExcelUtil.analyzeTitle(workbook, head);
//
//                String name = (String) titleMap.get("oname");
//                String mark = IndexUtil.getBrack(name, 1);
//
//                Organize organize = organizeDao.getByMark(mark);
//
//
//                if (!checkHeadOne(titleMap)) {
//                        logger.error("模板有误,请重新下载");
//                        return null;
//                } else {
//                        logger.info("模板正确");
//                }
//
//                HashMap<Integer, List<String[]>> contentMap = loadExcelUtil.analyzeContent(workbook, 1, head);
//                List<String[]> dates = contentMap.get(0);
//                List<Leaguer> leaguers = this.analyzeDate(dates, organize.getId());
//
//                leaguers = proofMessageService.addLeaguer(leaguers);
//
//                long endTime = System.currentTimeMillis();
//                logger.info("读取excel表格共花费{}毫秒", endTime - startTime);
//
//                return leaguers;
//        }

        public List<LoadMem> handleExcel(HSSFWorkbook workbook, String[] head) {
                long startTime = System.currentTimeMillis();

                HashMap<String, Object> titleMap = loadExcelUtil.analyzeTitle(workbook, head);

                String name = (String) titleMap.get("oname");
                String mark = IndexUtil.getBrack(name, 1);

                Organize organize = organizeDao.getByMark(mark);


                if (!checkHeadOne(titleMap) || !checkHeadTwo(titleMap)) {
                        logger.error("模板有误,请重新下载");
                        return null;
                } else {
                        logger.info("模板正确");
                }
                List<Department> departments = departmentDao.getLeaf(organize.getId());
                HashMap<Integer, List<String[]>> contentMap = loadExcelUtil.analyzeContent(workbook, departments.size(), head);

                List<LoadMem> members = new ArrayList<LoadMem>();
                List<LoadMem> loadMems = this.analyzeDate(contentMap, organize.getId(), departments);
                if (organize.getType() ==2){
                        loadMems = proofMessageService.proofMessageLeaguer(loadMems);
                        members = proofMessageService.addLeaguer(loadMems);
                }else {
                        loadMems = proofMessageService.proofMessage(loadMems);
                        members = proofMessageService.add(loadMems);
                }


                long endTime = System.currentTimeMillis();
                logger.info("读取excel表格共花费{}毫秒", endTime - startTime);

                return members;
        }


        public boolean checkHeadOne(HashMap<String, Object> hashMap) {
                String name = (String) hashMap.get("oname");
                String mark = IndexUtil.getBrack(name, 1);
                name = IndexUtil.getBrack(name, 0);
                Organize organize = organizeDao.getByMark(mark);
                if (organize == null) {
                        logger.error("模板有误(找不到该组织),请重新下载");
                }
                if (!name.equals(organize.getName())) {
                        logger.error("模板有误(内容不匹配),请重新下载");
                        return false;
                }
                return true;
        }

        public boolean checkHeadTwo(HashMap<String, Object> hashMap) {
                String name = (String) hashMap.get("oname");
                String mark = IndexUtil.getBrack(name, 1);

                List<String> deps = (List<String>) hashMap.get("deps");
                Organize organize = organizeDao.getByMark(mark);

                List<Department> departments = departmentDao.getLeaf(organize.getId());
                if (departments.size() != deps.size()) {
                        logger.error("模板有误(部门数量有误),请重新下载");
                        return false;
                }
                for (int i = 0; i < deps.size(); i++) {
                        String sql = departments.get(i).getName() + "(" + departments.get(i).getId() + ")";
                        if (!sql.equals(deps.get(i))) {
                                logger.error("模板有误(部门名有误),请重新下载");
                                return false;
                        }
                }
                return true;
        }

        public List<LoadMem> analyzeDate(HashMap<Integer, List<String[]>> contentMap,
                                         String oid, List<Department> deps) {
                List<LoadMem> loadMems = new ArrayList<LoadMem>();
                Organize organize = organizeDao.get(oid);
                int type = organize.getType();
                for (int i = 0; i < deps.size(); i++) {
                        List<String[]> dates = contentMap.get(i);
                        for (String[] data : dates) {
                                LoadMem loadMem = new LoadMem();
                                loadMem.setOid(oid);
                                loadMem.setDid(deps.get(i).getId());
                                loadMem.setMemberNum(data[0]);
                                if (type == 2){
                                       this.setUpMemberValue(loadMem,data);
                                }else {
                                        loadMem.setProName(data[1]);
                                }
                                loadMems.add(loadMem);
                        }
                }
                return loadMems;
        }

        public LoadMem setUpMemberValue(LoadMem loadMem, String[] data){
                loadMem.setMemberNum(data[0]);
                loadMem.setName(data[1]);
                loadMem.setMobile(data[2]);
                loadMem.setIntroduce(data[3]);
                loadMem.setSite(data[4]);
                String[] ms = data[2].split("/");
                List<String> mobiles = new ArrayList<String>();
                for (String m:ms){
                        mobiles.add(m);
                }
                loadMem.setMobiles(mobiles);
                return loadMem;
        }

        public List<LoadMem> analyzeDate(HashMap<Integer, List<String[]>> contentMap) {
                List<String[]> dates = contentMap.get(0);
                List<LoadMem> loadMems = new ArrayList<LoadMem>();
                for (String[] data : dates) {
                        LoadMem loadMem = new LoadMem();
                        this.setUpMemberValue(loadMem,data);
                        loadMems.add(loadMem);
                }
                return loadMems;
        }

        public void uploadFiles(MultipartFile file, String uploadDir) {
                FileUpLoadUtil.upload(file, uploadDir);

        }

        public String getFileOid(HSSFWorkbook workbook) {
                String oName = loadExcelUtil.getFileOid(workbook);
                String mark = IndexUtil.getBrack(oName, 1);
                return organizeDao.getByMark(mark).getId();
        }

        public boolean checkPow(String mid, String oid) {
              return managerService.checkManager(mid,oid);
        }

        public ResponseEntity<byte[]> download(String path, String oid) throws IOException {
                logger.info("开始下载模板文件");
                File file = new File(path);
                HttpHeaders headers = new HttpHeaders();
                String newName;
                if (organizeDao.get(oid) == null) {
                        newName = oid + ".xls";
                } else {
                        newName = organizeDao.get(oid).getName() + ".xls";
                }
                String fileName = new String(newName.getBytes("UTF-8"), "iso-8859-1");
                //为了解决中文名称乱码问题
                headers.setContentDispositionFormData("attachment", fileName);
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                logger.info("模板文件下载成功");
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
        }


        public List<LoadMem> handleExcelReg(HSSFWorkbook workbook, String[] head) {

                int groups = 1;
                HashMap<Integer, List<String[]>> contentMap = loadExcelUtil.analyzeContent(workbook, head, groups);

                List<LoadMem> loadMems = this.analyzeDate(contentMap);

                for (LoadMem member : loadMems) {
                        member.setCreateTime(DateFormatUtil.getYMdHm(new Date()));
                        if (memberLogDao.get(member.getMemberNum()) == null) {
                                logger.info("批量注册成员 [{}]成功", member.getMemberNum());
                                memberLogDao.register(member);
                        } else {
                                logger.info("批量注册成员 [{}失败", member.getMemberNum());
                        }
                        if (memberDao.getMsg(member.getMemberNum()) == null) {
                                logger.info("批量注册成员 [{}],完善信息成功", member.getMemberNum());
                                memberDao.complete(member);
                                member.setUpState(UpState.ADD);

                        } else {
                                logger.info("批量注册成员 [{}],添加信息失败", member.getMemberNum());
                                member.setUpState(UpState.IS_EXIST);
                        }
                }
                return loadMems;
        }

        public Organize get(String oid) {
                return organizeDao.get(oid);
        }

        public int getDepartmentSize(String oid) {
                return departmentDao.getByOid(oid).size();
        }

}
